<template>
    <a-spin tip="上传文件..." :spinning="loading" class="clearfix">
        <a-upload-dragger
            name="file"
            :multiple="false"
            :fileList="fileList"
            :customRequest="downloadFilesCustomRequest"
            :remove="removeFile"
        >
            <p class="ant-upload-drag-icon">
                <a-icon type="inbox" />
            </p>
            <p class="ant-upload-text">点击或拖拽上传文件</p>
        </a-upload-dragger>
    </a-spin>
</template>
<script>
import {uploadFile} from '@/api/upload'

export default{
    name:'UploadFile',
    props:{
        url:{
            type:String,
            default:''
        },
        name:{
            type:String,
            default:''
        }
    },
    data(){
        return{
            previewImage:'',
            previewVisible:false,
            loading:false,
        }
    },
    computed:{
        fileList(){
            let fileList = [];
            let url = this.url;
            if(url){
                let name = this.name || this.url.substring(this.url.lastIndexOf('/')+1);
                fileList.push({
                    uid:url,
                    status:'done',
                    name:name,
                    url:url
                })
            }
            return fileList;
        }
    },
    methods:{
        // 重写a-upload的文件上传处理方式
        async downloadFilesCustomRequest(data){
            console.log(data)
            this.loading = true;
            await this.saveFile(data)
        },
        // 上传并保存文件
        async saveFile(data){
            try{
                const formData = new FormData()  
                formData.append('file', data.file)  
                let res = await uploadFile(formData);
                let {data:imgUrl} = res;
                this.$emit('upload',{imgUrl,name:data.file.name})
            }catch(err){
                console.log(err)
            }finally{
                this.loading = false;
            }
        },
        //删除文件
        async removeFile(file){
            console.log(file)
            let {uid} = file;
            this.$emit('delete',uid)
        },
        handleCancel(){
            this.previewVisible = false;
        },
        async handlePreview(file){
            console.log(file)
            this.previewImage = file.url;
            this.previewVisible = true;
        },
    }
}
</script>
<style lang="scss" scoped>
.tip{
    margin: 0;
    line-height: 0;
    font-size: 12px;
    color: #999;
}
</style>
